package cn.exrick.manager.controller;


import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.manager.pojo.TbAdvice;
import cn.exrick.manager.pojo.TbUser;
import cn.exrick.manager.service.AdviceService;
import cn.exrick.manager.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
public class AdviceController {

    @Autowired
    private AdviceService adviceService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/advice/{adviceId}",method = RequestMethod.GET)
    public Result<TbAdvice> getAdviceById(@PathVariable Long adviceId){

        TbAdvice tbAdvice = adviceService.getAdviceById(adviceId);
        return new ResultUtil<TbAdvice>().setData(tbAdvice);
    }

    @RequestMapping(value = "/advice/list",method = RequestMethod.GET)
    public DataTablesResult getAdviceList(int draw, int start, int length,
                                        @RequestParam("order[0][column]") int orderCol, @RequestParam("order[0][dir]") String orderDir,
                                        String username, String startTime, String endTime){


        //获取客户端需要排序的列
        String[] cols = {"checkbox", "a.create_by", "a.create_time",  "a.advice", "a.reply"};
        String orderColumn = cols[orderCol];
        if(orderColumn == null) {
            orderColumn = "a.create_time";
        }
        //获取排序方式 默认为desc(asc)
        if(orderDir == null) {
            orderDir = "desc";
        }
        DataTablesResult result= adviceService.getAdviceList(draw,start,length,username,startTime,endTime,orderColumn,orderDir);
        return result;
    }

    /**
     * 回复建议
     * @param tbAdvice
     * @return
     */
    @RequestMapping(value = "/advice/reply",method = RequestMethod.POST)
    public Result<Object> reply(TbAdvice tbAdvice){
        String username = (String)SecurityUtils.getSubject().getPrincipal();
        TbUser user = userService.getUserByUsername(username);
        tbAdvice.setUpdateBy(user.getId());
        tbAdvice.setUpdateTime(new Date());
        adviceService.updateAdvice(tbAdvice);
        return new ResultUtil<>().setData(null);
    }

    /**
     * 删除建议
     * @param id
     * @return
     */
    @RequestMapping(value = "/advice/del/{id}",method = RequestMethod.POST)
    public Result<Object> delAdvice(@PathVariable Long id){
        adviceService.delAdvice(id);
        return new ResultUtil<>().setData(null);
    }

}
